using System.Reflection;
using Migrator.Providers.SQLite;
using NHibernate.Cfg;


namespace Wayloop.Blog.DataAccess
{
    public class MigrationRunner
    {
        private readonly Configuration configuration;


        /// <summary>
        /// Initializes a new instance of the <see cref="MigrationRunner"/> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        public MigrationRunner(Configuration configuration)
        {
            this.configuration = configuration;
        }


        public void MigrateToLastVersion()
        {
            Migrator.Migrator migrator = GetMigrator();
            migrator.MigrateToLastVersion();
        }


        private Migrator.Migrator GetMigrator()
        {
            Assembly migrationAssembly = Assembly.GetExecutingAssembly();
            string connectionString = GetConnectionString();
            var dialect = new SQLiteDialect();
            var transformationProvider = new SQLiteTransformationProvider(dialect, connectionString);

            return new Migrator.Migrator(transformationProvider, migrationAssembly, false);
        }


        private string GetConnectionString()
        {
            string connectionString = configuration.GetProperty("connection.connection_string");

            return connectionString;
        }
    }
}